package com.frain.springcloud.common;

import java.io.Writer;
import java.util.Date;
import java.util.regex.Pattern;

import com.frain.springcloud.response.message.ResponseTextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class XStreamUtil {

    public static XStream xstream = new XStream(new XppDriver() {

        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {

            return new PrettyPrintWriter(out) {
                boolean cdata = true;

                @Override
                protected void writeText(QuickWriter writer, String text) {

                    if (!isDate(text)) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }

                }

            };

        }

    });

    public static boolean isDate(String text) {

        try {
            if (text != null) {
                Date date = new Date(Long.parseLong(text));
                System.out.println(date);
                return true;

            }
        }
        catch (Exception e) {

        }

        return false;
    }

    public static boolean isNumber(String text) {

        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(text).matches();

    }

    public static String textMessagToXml(ResponseTextMessage message) {

        xstream.alias("xml", message.getClass());

        return xstream.toXML(message);
    }

    public static void main(String[] args) {

        System.out.println(isNumber("123456"));
        System.out.println(isNumber("ac5468d"));

        ResponseTextMessage message = new ResponseTextMessage();
        message.setContent("xiaoxicontent");
        message.setCreateTime(System.currentTimeMillis());
        message.setFromUserName("fromuserName");
        message.setMsgType("text");
        message.setToUserName("tousername");

        System.out.println(textMessagToXml(message));

    }
}
